import Singleton from "../net/Singleton";

export default class BundleManager extends Singleton {

    loadBundle(bundleName: string, assetPath: string, callback: Function = null) {
        let _bundle = this.getBundle(bundleName);
        if (_bundle) {
            this.bundleLoad(_bundle, assetPath, callback);
        } else {
            cc.assetManager.loadBundle(bundleName, (err: Error, bundle: cc.AssetManager.Bundle) => {
                if (err) {
                    cc.error(err);
                } else {
                    this.bundleLoad(bundle, assetPath, callback);
                }
            })
        }
    }

    bundleLoad(bundle: cc.AssetManager.Bundle, assetPath: string, callback: Function = null) {
        if(assetPath.includes('scene')){
            bundle.loadScene(assetPath, function (err, scene) {
                if (err) {
                    cc.error(err);
                } else {
                    callback && callback(scene);
                }
            });
        }else{
            bundle.load(assetPath, cc.Asset, (error: Error, asset: any) => {
                if (error) {
                    cc.error(error);
                } else {
                    callback && callback(asset);
                }
            });
        }
    }

    getBundle(bundleName: string) {
        return cc.assetManager.getBundle(bundleName);
    }

    removeBundle(bundleName: string) {
        let _bundle = this.getBundle(bundleName);
        if (_bundle) {
            cc.assetManager.removeBundle(_bundle);
        }
    }

    releaseAll(bundleName: string) {
        let _bundle = this.getBundle(bundleName);
        if (_bundle) {
            _bundle.releaseAll();
            cc.assetManager.removeBundle(_bundle);
        }
    }

}